#!/usr/bin/env python3

import os
import re
import sys
from glob import glob
from pathlib import Path
from zipfile import ZipFile

from binaryornot.check import is_binary

base_cwd = os.getcwd()
os.chdir(sys.argv[1])
cwd = Path.cwd().stem

for file in glob(str('**/*.py'), recursive=True):
	if not is_binary(file):
			import_path = str((Path(cwd)).joinpath(file).parent)
			import_path = import_path.replace('.py', '').replace('/', '.')

			with open(file, 'r', encoding='utf-8') as f:
				contents = f.read()

			# (from . )import -> (from qwe.asd )import
			contents = re.sub(r'from\s+\.\s+', f'from {import_path} ', contents)
			# (from .a)bc import -> (from zxc.a)bc import
			contents = re.sub(r'from\s+\.([a-zA-Z])', f'from {import_path}.\\1', contents)

			with open(file, 'w', encoding='utf-8') as f:
				f.write(contents)

os.chdir('..')
os.system(f'zip -qr {cwd}.zip {cwd}')
os.system(f'mv {cwd}.zip {base_cwd}')
